import useFetchData from '@ant-design/pro-descriptions/es/useFetchData';
import { useLocation } from '@umijs/max';
import { Typography } from 'antd';
import React, { useMemo } from 'react';
import DynamicComponent from '..';
import SfwLoadingContainer, {
  SfwLoadingContainerProps,
} from '../../common/SfwLoadingContainer';
import { emitComponentUse, queryDynamicComponent } from '../../services/dcApi';

export type CodeDynamicComponentProps = {
  /**
   * 组件编码，用于从服务器加载组件 schema 来渲染组件
   */
  componentCode: string;
  loadingContainer?: Omit<SfwLoadingContainerProps, 'queryResult'>;
};

const CodeDynamicComponent: React.FC<CodeDynamicComponentProps> = (props) => {
  const { componentCode, loadingContainer, ...restProps } = props;

  const location = useLocation();

  const [error, setError] = React.useState<any>();
  const fetchData = useMemo(() => {
    return async () => {
      const result = await queryDynamicComponent(componentCode);
      emitComponentUse(result?.data?.data);
      return result;
    };
  }, [componentCode, location.key]);
  const action = useFetchData<any>(fetchData, {
    manual: false,
    effects: [componentCode, location.key],
    onRequestError: (e) => setError(e),
  });
  const { loading, dataSource } = action;
  const queryResult = {
    loading,
    data: dataSource?.data,
    error: error,
  };
  const queryData = queryResult?.data || {};
  const schemaStr = queryData.dcSchema;

  const toJson = (schemaProps: string) => {
    if (!schemaProps) {
      return schemaProps;
    }
    try {
      return JSON.parse(schemaProps);
    } catch (e) {
      throw new Error(`schema不是一个正确的JSON，请检查。${schemaProps}`);
    }
  };
  const schema = toJson(schemaStr);

  return (
    <SfwLoadingContainer
      // tip={`组件加载中...`}
      queryResult={queryResult}
      emptyProps={{
        description: (
          <>
            动态组件【
            <Typography.Text strong type={'warning'}>
              {componentCode}
            </Typography.Text>
            】不存在
          </>
        ),
      }}
      {...loadingContainer}
    >
      <DynamicComponent schema={schema} {...restProps} />
    </SfwLoadingContainer>
  );
};

export default CodeDynamicComponent;
